//
//  ROHorizontalScrollListView.m
//  Runone
//
//  Created by runone02 on 16/12/1.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "ROHorizontalScrollListView.h"
#import "UIView+Addition.h"
#import "UIColor+Addition.h"


/*
 *  配置文件实现
 */
@implementation ListViewConfiguration

+ (instancetype) defaultConfiguration {
    
    ListViewConfiguration *LVConfig = [[ListViewConfiguration alloc] init];
    
    LVConfig.hasSelectedAnimation = YES;
    LVConfig.labelTextColor       = [UIColor lightGrayColor];
    LVConfig.spacing              = 15.0f;
    LVConfig.labelSelectedColor   = [UIColor colorWithHexString:@"#f7f7f7"];
    LVConfig.lineColor            = [UIColor lightGrayColor];
    LVConfig.labelFont            = [UIFont systemFontOfSize:17];
    
    return LVConfig;
}

- (void) setMonitorScrollView:(UIScrollView *)monitorScrollView {
    _monitorScrollView = monitorScrollView ;
    
    if (_monitorScrollViewWidth < 1) {
        [self setMonitorScrollViewWidth:[UIScreen mainScreen].bounds.size.width]; // 设置scrollView默认的宽度
        if (self.labelWidth < 1) {
            self.labelWidth = 50; // 设置默认的文本的宽度
        }
    }
}

@end

// ************************************-------  -------************************************

#define MainScreen                   [UIScreen mainScreen]

#define SCREEN_SCALE                 [MainScreen scale]

#define SINGLE_LINE_WIDTH            (0.25 * SCREEN_SCALE)

#define MyWidth                      self.bounds.size.width

static const CGFloat animateDuration = 0.3f; // 默认的动画时间

static const CGFloat lineHeight = 5.0f;      // 线条高度

@interface ROHorizontalScrollListView ()

@property (nonatomic, strong) ListViewConfiguration *configuration;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, assign) CGFloat itemScale;

@property (nonatomic, assign) CGFloat itemWidth;

@property (nonatomic, assign) NSInteger lastIndex;

@end

@implementation ROHorizontalScrollListView

static NSString *const offSetKeyPath = @"contentOffset";

#pragma mark - 初始化
+ (instancetype) listViewWithFrame:(CGRect)frame TextArray:(NSArray *)textArray Configuration:(ListViewConfiguration *)configuration {
    return [[self alloc] initWithFrame:frame TextArray:textArray Configuration:configuration];
}

+ (instancetype)listViewWithFrame:(CGRect)frame TextArray:(NSArray *)textArray {
    return [[self alloc] initWithFrame:frame TextArray:textArray];
}

- (instancetype)initWithFrame:(CGRect)frame
                    TextArray:(NSArray *)textArray
                Configuration:(ListViewConfiguration *)configuration {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
#pragma mark 执行顺序不能错
        
        self.configuration = configuration;
        
        if (self.configuration.monitorScrollView) {
            [self.configuration.monitorScrollView addObserver:self forKeyPath:offSetKeyPath options:NSKeyValueObservingOptionNew context:(__bridge void * _Nullable)(self)];
            
            self.itemWidth = self.configuration.labelWidth;
            self.itemScale = self.itemWidth / self.configuration.monitorScrollViewWidth;
        }
        
        
        [self setupSubviews];
        
        if (textArray.count > 0) {
            self.labelTextArray = textArray;
        }
        
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame TextArray:(NSArray *)textArray {
    
    ROHorizontalScrollListView *listView = [[ROHorizontalScrollListView alloc] initWithFrame:frame];
    
    listView.labelTextArray = textArray;
    
    return listView;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupSubviews];
    }
    return self;
}

#pragma mark - 布局子控件
- (void)setupSubviews {
    
    [self setupScrollView];
    [self setupLineView];
    [self setupBottomView];
    
}

- (void)setupScrollView {
    
    UIScrollView *sc = [UIScrollView new];
    sc.showsHorizontalScrollIndicator = NO;
    sc.bounces = NO;
    
    [self addSubview:sc];
    
    self.scrollView = sc;
}

- (void)setupBottomView {
    CGFloat line_h = SINGLE_LINE_WIDTH;
    
    CALayer *line = [CALayer layer];
    line.backgroundColor = [[UIColor alloc] initWithWhite:0.9 alpha:1].CGColor;
    [line setFrame:CGRectMake(0,self.height - line_h,self.width,line_h)];
    [self.layer addSublayer:line];
    
    _bottomLayer = line;
}

- (void)setupLineView {
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0,self.height - lineHeight,0, lineHeight)];
    lineView.backgroundColor = self.configuration.lineColor;
    [self.scrollView addSubview:lineView];
    
    _lineView = lineView;
}

- (void)setupTitleLabel{
    
    _titleLabelArray = [[NSMutableArray alloc] initWithCapacity:self.labelTextArray.count];
    
    for (NSInteger index = 0; index < self.labelTextArray.count; index++) {
        
        NSString *text = [self.labelTextArray objectAtIndex:index];
        
        UILabel *label = [UILabel new];
        
        label.font                   = self.configuration.labelFont;
        label.userInteractionEnabled = YES;
        label.textAlignment          = NSTextAlignmentCenter;
        label.tag                    = index;
        label.text                   = text;
        label.textColor              = [UIColor blackColor];
        UITapGestureRecognizer *tap  = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelDidTap:)];
        [label addGestureRecognizer:tap];
        
        [self.scrollView addSubview:label];
        [_titleLabelArray addObject:label];
    }
}
#pragma  mark - label点击
- (void)labelDidTap:(UITapGestureRecognizer *)tap {
    
    UILabel *selectLabel = (UILabel *)[tap view];// 获取tap的view
    
    if (self.currentSelectedLabel == selectLabel) return;
    
    [self selectItem:selectLabel];
}

- (void)selectItem:(UILabel *)selectLabel {
    
    if (self.configuration.monitorScrollView) {
        
        CGFloat offsetX = self.configuration.monitorScrollViewWidth * selectLabel.tag;
        
        BOOL animate = YES;
        
        if (labs(_currentSelectedLabel.tag - selectLabel.tag) > 2) animate = NO;
        
        [self.configuration.monitorScrollView setContentOffset:CGPointMake(offsetX, 0) animated:animate];
    }else {
        [self scrollWithOffsetX:selectLabel.center.x];
    }
}

- (void)scrollWithOffsetX:(CGFloat)x {
    
    [_lineView setX:x + self.configuration.spacing * 0.5];
    
    _currentIndex = round(x/(self.itemWidth));
    
    //如果和lastIndex一样,或者出现越界的现象,直接return
    
    if (self.lastIndex == _currentIndex ||
        _currentIndex >= _titleLabelArray.count ||
        _currentIndex < 0) return;
    
    self.lastIndex = _currentIndex;
    
    UILabel *currentLabel = _titleLabelArray[_currentIndex];
    
    [self setCurrentSelectLabel:currentLabel];
    
    CGFloat left = x - MyWidth * 0.5f;
    CGFloat right = self.scrollView.contentSize.width - MyWidth;
    
    if (left < 0) {
        left = 0;
    }else if (left > right) {
        left = right;
    }
    
    [self.scrollView setContentOffset:CGPointMake(left, 0) animated:YES];
    
    if (self.selectedAtIndex) {
        self.selectedAtIndex(currentLabel.tag);
    }
}
- (void)setCurrentSelectLabel:(UILabel *)newSelectLabel {
    
    [UIView animateWithDuration:animateDuration animations:^{
        
        _currentSelectedLabel.textColor = self.configuration.labelTextColor;
        
        newSelectLabel.textColor = self.configuration.labelSelectedColor;
        
        if (self.configuration.hasSelectedAnimation) {
            
            _currentSelectedLabel.transform = CGAffineTransformIdentity;
            
            newSelectLabel.transform = CGAffineTransformMakeScale(1.2, 1.2);
        }
        
    }];
    _currentSelectedLabel = newSelectLabel;
    
}

- (void)setLabelTextArray:(NSArray *)labelTextArray {
    _labelTextArray = labelTextArray;
    
    [self setupTitleLabel];
    
    [self calculateLabelFrame];
    
    [self setCurrentSelectLabel:(UILabel *)_titleLabelArray.firstObject];
    
    if (self.itemWidth > 1) {
        [_lineView setWidth:self.configuration.labelWidth - self.configuration.spacing];
        [_lineView setX:self.configuration.spacing * 1.5];
    }else {
        CGRect firstFrame = [_titleLabelFrameCache.firstObject CGRectValue];
        [_lineView setWidth:firstFrame.size.width];
        [_lineView setX:firstFrame.origin.x + self.configuration.spacing];
    }
}

- (void)calculateLabelFrame {
    
    _titleLabelFrameCache = [[NSMutableArray alloc] initWithCapacity:_titleLabelArray.count];
    
    
    for (NSInteger index = 0; index < _titleLabelArray.count; index++) {
        
        
        CGSize labelSize;
        
        if (self.configuration.labelWidth < 1) {
            //如果没设置labelSize 计算并采用文本size
            NSString *text = [self.labelTextArray objectAtIndex:index];
            
            CGSize textSize = [text boundingRectWithSize:CGSizeMake(MAXFLOAT,self.height)
                                                 options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
                                              attributes:@{NSFontAttributeName:self.configuration.labelFont} context:nil].size;
            
            labelSize = textSize;
            
        }else {
            
            labelSize = CGSizeMake(self.configuration.labelWidth, self.height);
            
        }
        
        
        CGFloat label_X = self.configuration.spacing;
        
        if (index > 0) {
            
            NSValue *lastFrame = [_titleLabelFrameCache objectAtIndex:index - 1];
            
            label_X = CGRectGetMaxX([lastFrame CGRectValue]);
            
        }
        
        
        CGRect labelFrame = CGRectMake(label_X,
                                       (self.height - labelSize.height) * 0.5,
                                       labelSize.width, labelSize.height);
        
        UILabel *currentLabel = [_titleLabelArray objectAtIndex:index];
        
        [currentLabel setFrame:labelFrame];
        
        //缓存Frame
        [_titleLabelFrameCache addObject:[NSValue valueWithCGRect:labelFrame]];
        
    }
    
    CGFloat MAX_X = CGRectGetMaxX([[_titleLabelFrameCache lastObject] CGRectValue]) + self.configuration.spacing;
    
    self.scrollView.contentSize = CGSizeMake(MAX_X, 0);
}

- (void)updateLabelFrame {
    
    
    for (NSInteger index = 0; index < _titleLabelArray.count; index++) {
        
        UILabel *currentLabel = [_titleLabelArray objectAtIndex:index];
        
        [currentLabel setFrame:[[_titleLabelFrameCache objectAtIndex:index] CGRectValue]];
        
    }
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    self.scrollView.frame = self.bounds;
    
    CGFloat line_h = SINGLE_LINE_WIDTH;
    //
    //    [_lineView   setFrame:CGRectMake(_lineView.x,self.height - lineHeight,0, lineHeight)];
    [_bottomLayer setFrame:CGRectMake(0,self.height - line_h,self.width,line_h)];
    //
    if (_titleLabelArray.count < 1) return;
    
    [self updateLabelFrame];
    
    
}

- (ListViewConfiguration *)configuration {
    if (_configuration == nil) {
        _configuration = [ListViewConfiguration defaultConfiguration];
    }
    return _configuration;
}




@end
